package com.example.springjdbcorm.test;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class JdbcV1 {

    public static void main(String[] args) {
        User user = new User();
        user.setId(1);
        List<Object> list = (List<Object>) queryList(user);
        for (Object o : list) {
            User u =(User)o;
            System.out.println(u.toString());
        }
    }


    public static List<?> queryList(Object object){
        List<Object> list = new ArrayList<>();
        StringBuffer sql = new StringBuffer();
        StringBuffer whereSql = new StringBuffer();
        Boolean isWhere = false;
        Boolean isAnd = false;
        //条件查询判断
        Class clazz = object.getClass();
        String tableName= clazz.getSimpleName();//类名 = 表明
        sql.append("select * from ").append(tableName);//拼接查询表名
        //遍历所有字段并判断是否不为空
        Field[] fields = clazz.getDeclaredFields();
        for (int i = 0; i<fields.length;i++){
            Field field = fields[i];
            field.setAccessible(true);
            try {
                Object filedValue = field.get(object);
                if(null != filedValue && (!filedValue.toString().equals(""))){//判断是否赋值
                    isWhere = true;//设置存在条件查询标记
                    if(isAnd) {whereSql.append(" and ");}//如果不是第一次追加条件则拼接and
                    whereSql.append(field.getName()).append(" ").append("=").append(filedValue.toString()).append(" ");
                    isAnd = true;
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        if(isWhere) {sql.append(" where ").append(whereSql);}//判断是否需要追加where
        //执行SQL
        System.err.println(sql.toString()+"++++++++++++++++++++++++++++++");
        ResultSet resultSet = query(sql.toString());
        //结果封装
        if (null != resultSet){
            try{
                while (resultSet.next()){
                    Object entity = Class.forName(object.getClass().getName());//实例化一个实体类
                    fields = entity.getClass().getDeclaredFields();
                    System.out.println(fields.toString());
                    for (int j = 0; j < fields.length; j++) {
                        Field field = fields[j];
                        field.setAccessible(true);//暴力访问
                        String fieldType = field.getGenericType().toString();//属性类型
                        System.out.println(fieldType);
                        System.out.println(field.getName());
                        if(field.getType().isPrimitive()){
                            continue;
                        }else if (fieldType.equals("int")){
                            field.set(entity,resultSet.getInt(field.getName()));//为属性赋值
                        }else if (fieldType.equals("String")){
                            field.set(entity,resultSet.getString(field.getName()));//为属性赋值
                        }
                    }
                    list.add(entity);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return list;
    }

    private static ResultSet query(String sql){

        try {
            //加载驱动
            //Class.forName("com.mysql.jdbc.Driver");//spring自动注入了驱动不用加载
            //建立连接
            Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jdbc-orm?serverTimezone=UTC","root","root");
            //创建语句集
            CallableStatement callableStatement = connection.prepareCall(sql);
            //执行语句集
            ResultSet result = callableStatement.executeQuery();
//            connection.close();
//            callableStatement.close();
//            result.close();
            return result;
        } catch ( SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
